package cn.regexp.web.controller;

import cn.regexp.domain.ShopConsignee;
import cn.regexp.query.ConsigneeQuery;
import cn.regexp.service.IConsigneeService;
import cn.regexp.utils.CommonUtil;
import cn.regexp.utils.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("consignees")
public class ConsigneeController {
    @Autowired
    private IConsigneeService consigneeService;

    @GetMapping("/query")
    @ApiOperation(value = "查找收货人列表", notes = "查找指定用户的收货人列表")
    public JsonResult<List<ShopConsignee>> query(ConsigneeQuery qo) {
        QueryWrapper<ShopConsignee> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", ShopConsignee.DELETE_NO)
                .eq("user_id", qo.getUserId());
        List<ShopConsignee> consigneeList = consigneeService.list(wrapper);
        // 遍历收件人，拼接地址
        consigneeList.forEach(item -> item.setFullAddress(CommonUtil.getFullAddress(item)));
        return JsonResult.success(consigneeList);
    }



    @GetMapping("/getOne")
    @ApiOperation(value = "通过 id 查找收货人", notes = "通过 id 查找收货人")
    public JsonResult<ShopConsignee> getOne(Long id) {
        ShopConsignee consignee = consigneeService.getById(id);
        if (ShopConsignee.DELETE_NO == consignee.getIsDel()) {
            consignee.setFullAddress(CommonUtil.getFullAddress(consignee));
        } else {
            consignee = null;
        }
        return JsonResult.success(consignee);
    }

    @PostMapping("/saveConsignee")
    @ApiOperation(value = "保存收货人", notes = "保存收货人")
    public JsonResult<String> saveConsignee(@RequestBody ShopConsignee consignee) {
        return consigneeService.saveConsignee(consignee) ? JsonResult.success("保存成功") : JsonResult.defaultError();
    }

    @PostMapping("/delConsignee")
    @ApiOperation(value = "删除收货人", notes = "删除收货人")
    public JsonResult<String> delConsignee(@RequestBody Long id) {
        ShopConsignee consignee = new ShopConsignee();
        consignee.setIsDel(ShopConsignee.DELETE_YES);
        consignee.setId(id);
        return consigneeService.updateById(consignee) ? JsonResult.success("删除成功") : JsonResult.defaultError();
    }

    @GetMapping("/getDefaultConsignee")
    @ApiOperation(value = "获取默认收货人", notes = "根据用户 id 获取默认收货人")
    public JsonResult<ShopConsignee> getDefaultConsignee(Long id) {
        QueryWrapper<ShopConsignee> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id)
                .eq("is_del", ShopConsignee.DELETE_NO)
                .eq("is_default", Boolean.TRUE);
        ShopConsignee consignee = consigneeService.getOne(wrapper);
        consignee.setFullAddress(CommonUtil.getFullAddress(consignee));
        return JsonResult.success(consignee);
    }
}
